package com.iad.controller.manager {
  import com.adobe.cairngorm.control.CairngormEvent;
  import com.adobe.cairngorm.control.CairngormEventDispatcher;
  import com.iad.controller.event.*;
  import com.iad.model.*;
  
  import flash.events.EventDispatcher;
  
  import mx.controls.Alert;
  import mx.events.BrowserChangeEvent;
  import mx.managers.BrowserManager;
  import mx.managers.IBrowserManager;
  import mx.utils.URLUtil;
  
  public class DeepLinkManager extends EventDispatcher
  {
    [Bindable] private var model:ModelLocatorImpl = ModelLocatorImpl.getInstance();
    
    private var isParsing:Boolean;
    
    private static var _instance:DeepLinkManager;
    
    public var browserManager:IBrowserManager = BrowserManager.getInstance();
  
    public function DeepLinkManager()  {
      if (_instance != null) {
        trace("Only one instance of DeepLinkManager can be instantiated");
      }
      browserManager = BrowserManager.getInstance();
      browserManager.init("", model.DEFAULT_BROWSER_TITLE + " - " + model.DEFAULT_ISSUE_DATE_TITLE);
      browserManager.addEventListener(BrowserChangeEvent.BROWSER_URL_CHANGE, parseURL);
    }
    
    public function parseURL(event:Event = null):void {
      trace('PARSE URL:' + browserManager.fragment);
      isParsing = true;
      var o:Object = URLUtil.stringToObject(browserManager.fragment);
      isParsing = false;    
      if (o.site != undefined) {
        model.currentSiteLabel = o.site as String;
        CairngormEventDispatcher.getInstance().dispatchEvent(new SiteEvent(SiteEvent.GET_SITE_BY_LABEL, model.currentSiteLabel));
      }
      else {
        model.app.currentState = model.MAIN_VIEW; 
      }
    }
  
    public function updateURL(pathLabel:String, siteName:String):void {
      trace('UPDATE URL:' + pathLabel);
      var fragments:String = "";
      var o:Object = {};
      if (pathLabel != null) {
        o.site = pathLabel;
        fragments = URLUtil.objectToString(o);
      }
      browserManager.setTitle(model.DEFAULT_BROWSER_TITLE + " - " + siteName);
      browserManager.setFragment(fragments);
    }

    
    public static function getInstance():DeepLinkManager {
      if (_instance == null)  {
        _instance = new DeepLinkManager();
      }
      return _instance;
    }
    
  }
}